package com.yichi;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.yichi.device_bean.BatteryStore;
import com.yichi.device_bean.BmsParam;
import com.yichi.device_bean.PlcInfo;
import com.yichi.global.PlatformResult;
import com.yichi.service.DeviceService;
import com.yichi.service.IccardService;
import com.yichi.service.MqttService;
import com.yichi.service.PlatformService;
import com.yichi.service.PlcService;
import com.yichi.util.BeanUtil;
import com.yichi.util.MapUtil;
import com.yichi.util.StringUtil;
import com.yichi.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

public class FaceOperTipFragment extends Fragment {

    private final static String TAG = "QuDianTipFragment";

    private TextView tip1, tip2;
    private String str1, str2;
    int i;

    private Integer operType;//操作类型：1取电 2还电
    private BatteryStore batteryStore;
    private Map<String, Object> dataMap;
    private Integer orderId;

    public FaceOperTipFragment() {

    }

    public FaceOperTipFragment(String str1, String str2, BatteryStore batteryStore, Map<String, Object> dataMap, Integer operType) {
        this.str1 = str1;
        this.str2 = str2;
        this.batteryStore = batteryStore;
        this.dataMap = dataMap;
        this.operType = operType;

        this.orderId = MapUtil.getInteger(dataMap, "id");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_face_oper_tip, container, false);
        findView(view);
        tip1.setText(this.str1);
        tip2.setText(this.str2);
//        setView();
        startHandleTask();
        return view;
    }

    private void setView() {
        tip2.setOnClickListener(view -> {
            int index = i % 4;
            switch (index) {
                case 0:
                    tip1.setText("用户张**的订单进行中");
                    tip2.setText("仓门已开，请取电，取出后\n请关闭仓门");
                    break;
                case 1:
                    tip1.setText("用户张**正在存电，请按照提示操作");
                    tip2.setText("正在开门请稍等\n请留意仓门");
                    break;
                case 2:
                    tip1.setText("用户张**正在取电，请按照提示操作");
                    tip2.setText("电池已取走\n请关闭仓门");
                    break;
                case 3:
                    tip1.setText("用户张**正在取电，请按照提示操作");
                    tip2.setText("仓门已开，请存电\n存入后请关闭仓门");
                    break;

            }
            i++;
        });
    }

    private void findView(View view) {
        tip1 = view.findViewById(R.id.tip1);
        tip2 = view.findViewById(R.id.tip2);
    }

    /**
     * 开始执行
     */
    private void startHandleTask() {
        Executors.newSingleThreadExecutor().execute(()->{
            if (operType.equals(1)) {
                handleQD();
            } else {
                handleCD();
            }
        });
    }

    /**
     * 执行取电操作
     */
    private void handleQD() {
        //1 等待一下
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //2 开仓门
        PlcService.inst.handleOpenDoor(batteryStore.getStoreNo());
        Log.i(TAG, String.format("扫脸取电，开仓门%s", batteryStore.getStoreNo()));

        //3 门是否开了
        boolean openDoor = PlcService.inst.isOpenDoor(batteryStore.getStoreNo());
        Log.i(TAG, String.format("扫脸取电，开仓门%s", openDoor));
        if (!openDoor) {
            PlatformResult result = new PlatformResult(500, "take_battery", "取电失败：仓门未打开");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", orderId);
            dataMap.put("cabinetID", batteryStore.getStoreNo());
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(getContext(), "取电失败：仓门未打开");
                goHome();
            });
            return;
        }
        batteryStore.setDoorOpen(true);
        DeviceService.inst.saveData();
        requireActivity().runOnUiThread(()->{
            tip2.setText("仓门已开，请取电，取出后\n请关闭仓门");
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //4 mqtt提交。操作成功：电池信息
        PlatformResult result = new PlatformResult(200, "take_battery", "仓门打开成功");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderId", orderId);
        dataMap.put("cabinetID", batteryStore.getStoreNo());
        dataMap.put("batteryNum", batteryStore.getBatteryNo());
        BmsParam bmsParam = batteryStore.getBmsParam();
        if (bmsParam != null) {
            dataMap.put("batteryState", "");
            dataMap.put("batteryCapacity", bmsParam.getSoc());
            dataMap.put("batteryVoltage", bmsParam.getTotalVoltage());
            dataMap.put("batteryMileage", batteryStore.getBatteryMileage());
        } else {
            dataMap.put("batteryState", "");
            dataMap.put("batteryCapacity", 80);
            dataMap.put("batteryVoltage", 55);
            dataMap.put("batteryMileage", 45);
        }
        result.setData(dataMap);
        MqttService.inst.sendMsg(result.toJsonString());
        Log.i(TAG, "提交平台成功");

        //5 门是否关闭
        PlcInfo closeDoor = PlcService.inst.isCloseDoor(batteryStore.getStoreNo());
        batteryStore.setDoorOpen(false);
        DeviceService.inst.saveData();
        Integer batteryStatus = closeDoor.getBatteryStatusByStoreNo(batteryStore.getStoreNo());
        if (batteryStatus.equals(0)) {
            //电池取走了
            BeanUtil.setBatteryStoreEmpty(batteryStore);
            DeviceService.inst.saveData();
            PlatformService.updateIsTakeBattery(orderId.toString());//http提交，已取走电池
        }
        PlatformService.updateTakeCloseDoor(orderId.toString());//httpt提交，已关门
        Log.i(TAG, String.format("扫脸取电，门已关闭"));

        //6 回首页
        requireActivity().runOnUiThread(()->{
            goHome();
        });
        Log.i(TAG, "扫脸取电，操作完成");
    }

    private void goHome() {
        MainActivity mainActivity = (MainActivity) requireActivity();
        mainActivity.goHome();
    }

    /**
     * 执行存电操作
     */
    private void handleCD() {
        //1 等待一下
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //2 开仓门
        PlcService.inst.handleOpenDoor(batteryStore.getStoreNo());
        Log.i(TAG, String.format("扫脸存电，开仓门%s", batteryStore.getStoreNo()));

        //3 门是否开了
        boolean openDoor = PlcService.inst.isOpenDoor(batteryStore.getStoreNo());
        Log.i(TAG, String.format("扫脸存电，开仓门%s", openDoor));
        if (!openDoor) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：仓门未打开");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", orderId);
            dataMap.put("cabinetID", batteryStore.getStoreNo());
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(getContext(), "还电失败：仓门未打开");
                goHome();
            });
            return;
        }
        batteryStore.setDoorOpen(true);
        DeviceService.inst.saveData();
        requireActivity().runOnUiThread(()->{
            tip2.setText("仓门已开，请放入电池\n放入后请关闭仓门");
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //4 门是否关闭
        PlcInfo closeDoor = PlcService.inst.isCloseDoor(batteryStore.getStoreNo());
        if (closeDoor == null) {
            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(getContext(), "还电失败：操作已中断");
                goHome();
            });
            return;
        }
        batteryStore.setDoorOpen(false);
        DeviceService.inst.saveData();
        Log.i(TAG, "门关了");

        //8 是否有电池
        String[] batteryNoArr = IccardService.inst.queryBatteryNo();
        if (batteryNoArr == null || batteryNoArr.length < 3) {
            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(getContext(), "还电失败：没放入电池");
                goHome();
            });
            return;
        }
        String batteryNo = batteryNoArr[batteryStore.getStoreNo() - 1];
        if (StringUtil.isEmpty(batteryNo)) {
            requireActivity().runOnUiThread(() -> {
                ToastUtil.show(getContext(), "还电失败：没放入电池");
                goHome();
            });
            return;
        }
        Log.i(TAG, "扫脸存电：已放入电池：" + batteryNo);
        batteryStore.setHasBattery(true);
        batteryStore.setBatteryNo(batteryNo);
        batteryStore.setLockStatus(0);
        DeviceService.inst.saveData();

        //9 提交平台操作成功了
        PlatformResult result = new PlatformResult(200, "return_battery", "电池归还成功");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderId", orderId);
        dataMap.put("cabinetID", batteryStore.getStoreNo());
        dataMap.put("batteryNum", batteryNo);
        result.setData(dataMap);
        MqttService.inst.sendMsg(result.toJsonString());
        Log.i(TAG, "提交平台完成");

        //10 回首页
        requireActivity().runOnUiThread(()->{
            goHome();
        });
        Log.i(TAG, "扫脸存电，操作完成");
    }
}
